/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ManagerFrame.java
 *
 * Created on 20.12.2008, 20:53:43
 */

package gui.manager;

import gui.templates.TemplatePanel;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;

import logic.Report;
import logic.Template;
import logic.TemplateEntry;
import ui.logger.GlobalLogger;
import ui.logger.LogEvent;
import client.Factory;

import com.pallas.swing.date.DateComboBox;

/**
 * 
 * @author re_agent
 */
public class ManagerFrame extends javax.swing.JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2809562838803839502L;
	private Template salesTemplate;
	private Template rentTemplate;

	/** Creates new form ManagerFrame */
	public ManagerFrame() {
		try {
			salesTemplate = Factory.getFactory().getTemplateRetriever().get("sales", "");
			rentTemplate = Factory.getFactory().getTemplateRetriever().get("rent", "");
		} catch (RemoteException e) {
			GlobalLogger.getInstance().show(new LogEvent(e));
			e.printStackTrace();
		} catch (RuntimeException e) {
			GlobalLogger.getInstance().show(new LogEvent(e));
			e.printStackTrace();
		}

		initComponents();
		cbTypeActionPerformed(null);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {
		setTitle("Отчеты и шаблоны");
		reportPanel = new javax.swing.JPanel();
		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();
		tfAgent = new javax.swing.JTextField();
		jLabel3 = new javax.swing.JLabel();
		cbType = new javax.swing.JComboBox();
		jLabel4 = new javax.swing.JLabel();
		generate = new javax.swing.JButton();
		cbField = new javax.swing.JComboBox();
		jLabel5 = new javax.swing.JLabel();
		jPanel1 = new javax.swing.JPanel();
		sale = new javax.swing.JButton();
		rent = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setMinimumSize(new java.awt.Dimension(0, 265));

		reportPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory
				.createTitledBorder(""), "Генерация отчетов"));

		jLabel1.setText("Период с");

		jLabel2.setText("По");

		tfAgent.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				tfAgentActionPerformed(evt);
			}
		});

		jLabel3.setText("Агент");

		cbType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Акт продажи", "Акт аренды" }));
		cbType.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				cbTypeActionPerformed(evt);
			}
		});

		jLabel4.setText("Тип документа");

		generate.setText("Сгенерировать");
		generate.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				generateActionPerformed(evt);
			}
		});

		cbField.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

		jLabel5.setText("Поле документа");

		dateFrom = new com.pallas.swing.date.DateComboBox();
		dateTo = new com.pallas.swing.date.DateComboBox();

		javax.swing.GroupLayout reportPanelLayout = new javax.swing.GroupLayout(reportPanel);
		reportPanel.setLayout(reportPanelLayout);
		reportPanelLayout.setHorizontalGroup(reportPanelLayout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				reportPanelLayout.createSequentialGroup().addGroup(
						reportPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
								reportPanelLayout.createSequentialGroup().addGroup(
										reportPanelLayout
												.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jLabel1).addComponent(dateFrom, 0, 98, Short.MAX_VALUE))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(
												reportPanelLayout.createParallelGroup(
														javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(jLabel2).addComponent(dateTo, 0, 98,
																Short.MAX_VALUE)).addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(
												reportPanelLayout.createParallelGroup(
														javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(jLabel3).addComponent(tfAgent,
																javax.swing.GroupLayout.DEFAULT_SIZE, 82,
																Short.MAX_VALUE)).addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(
												reportPanelLayout.createParallelGroup(
														javax.swing.GroupLayout.Alignment.LEADING).addComponent(cbType,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel4))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(
												reportPanelLayout.createParallelGroup(
														javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(jLabel5).addComponent(cbField, 0, 106,
																Short.MAX_VALUE))).addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								reportPanelLayout.createSequentialGroup().addContainerGap(382, Short.MAX_VALUE)
										.addComponent(generate, javax.swing.GroupLayout.PREFERRED_SIZE, 133,
												javax.swing.GroupLayout.PREFERRED_SIZE))).addGap(9, 9, 9)));
		reportPanelLayout.setVerticalGroup(reportPanelLayout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				reportPanelLayout.createSequentialGroup().addGroup(
						reportPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(
								jLabel1).addComponent(jLabel2).addComponent(jLabel3).addComponent(jLabel4)
								.addComponent(jLabel5)).addPreferredGap(
						javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(
						reportPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(
								dateFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(dateTo,
								javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(cbType,
								javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(tfAgent,
								javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(cbField,
								javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(
						javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE,
						Short.MAX_VALUE).addComponent(generate)));

		jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(
				javax.swing.BorderFactory.createTitledBorder(""), "Редактирование шаблонов документов"));

		sale.setText("Акт продажи");
		sale.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				saleActionPerformed(evt);
			}
		});

		rent.setText("Акт аренды");
		rent.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				rentActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						jPanel1Layout.createSequentialGroup().addGroup(
								jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
										.addComponent(rent, javax.swing.GroupLayout.Alignment.LEADING,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(
												sale, javax.swing.GroupLayout.Alignment.LEADING,
												javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
								.addContainerGap(289, Short.MAX_VALUE)));
		jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						jPanel1Layout.createSequentialGroup().addComponent(sale).addPreferredGap(
								javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(rent)));

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				layout.createSequentialGroup().addContainerGap().addGroup(
						layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(reportPanel,
								javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 544,
								Short.MAX_VALUE).addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addContainerGap()));
		layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				layout.createSequentialGroup().addContainerGap().addComponent(reportPanel,
						javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(
						javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jPanel1,
						javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
						Short.MAX_VALUE)));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void generateActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_generateActionPerformed
		try {
			Report r = Factory.getFactory().getReporter()
					.report(
							tfAgent.getText(),
							((cbType.getSelectedIndex() == 0) ? "sales" : "rent") + ":"
									+ ((TemplateEntry) cbField.getSelectedItem()).getId(), dateFrom.getDate(),
							dateTo.getDate());
			r.setEntry((TemplateEntry) cbField.getSelectedItem());
			JDialog dialog = new JDialog();
			dialog.setModal(true);

			JTextArea view = new JTextArea(r.print());
			view.setFont(getFont());
			dialog.add(new JScrollPane(view));
			dialog.setTitle(r.getHeader());
			dialog.pack();
			dialog.setVisible(true);
			// System.out.println(r.print());
		} catch (RemoteException e) {
			GlobalLogger.getInstance().show(new LogEvent(e));
			e.printStackTrace();
		} catch (RuntimeException e) {
			GlobalLogger.getInstance().show(new LogEvent(e));
			e.printStackTrace();
		}
	}// GEN-LAST:event_generateActionPerformed

	private void saleActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_saleActionPerformed
		TemplatePanel templatePanel = new TemplatePanel(salesTemplate);
		if (showDialog(templatePanel)) {
			Template reconstructTemplate = templatePanel.reconstructTemplate();
			salesTemplate = reconstructTemplate;
			salesTemplate.setTemplateCode("sales");
			try {
				Factory.getFactory().getTemplateRetriever().set("sales", reconstructTemplate, "");
			} catch (RemoteException e) {
				GlobalLogger.getInstance().show(new LogEvent(e));
				e.printStackTrace();
			} catch (RuntimeException e) {
				GlobalLogger.getInstance().show(new LogEvent(e));
				e.printStackTrace();
			}
		}
	}// GEN-LAST:event_saleActionPerformed

	private void rentActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_rentActionPerformed
		TemplatePanel templatePanel = new TemplatePanel(rentTemplate);
		if (showDialog(templatePanel)) {
			Template reconstructTemplate = templatePanel.reconstructTemplate();
			rentTemplate = reconstructTemplate;
			rentTemplate.setTemplateCode("rent");
			try {
				Factory.getFactory().getTemplateRetriever().set("rent", reconstructTemplate, "");
			} catch (RemoteException e) {
				GlobalLogger.getInstance().show(new LogEvent(e));
				e.printStackTrace();
			} catch (RuntimeException e) {
				GlobalLogger.getInstance().show(new LogEvent(e));
				e.printStackTrace();
			}
		}
	}// GEN-LAST:event_rentActionPerformed

	private boolean showDialog(TemplatePanel templatePanel) {
		final JDialog dialog = new JDialog();
		dialog.setModal(true);
		dialog.setTitle("Редактирование шаблона");
		// dialog.setSize(300, 500);
		dialog.setLayout(new BorderLayout());
		dialog.add(templatePanel, BorderLayout.NORTH);
		final boolean[] saved = new boolean[1];
		JPanel p = new JPanel();
		((JButton) p.add(new JButton("Отмена"))).addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				dialog.setVisible(false);
				saved[0] = false;
			}
		});
		((JButton) p.add(new JButton("Сохранить"))).addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				dialog.setVisible(false);
				saved[0] = true;
			}
		});
		dialog.add(p, BorderLayout.SOUTH);
		dialog.pack();
		dialog.setVisible(true);
		return saved[0];
	}

	private void tfAgentActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_tfAgentActionPerformed
		// TODO add your handling code here:
	}// GEN-LAST:event_tfAgentActionPerformed

	private void cbTypeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cbTypeActionPerformed
		cbField.setSelectedIndex(0);
		if (cbType.getSelectedIndex() == 0)
			cbField.setModel(new DefaultComboBoxModel(salesTemplate.allEntries()));
		else
			cbField.setModel(new DefaultComboBoxModel(rentTemplate.allEntries()));
		cbField.invalidate();

	}// GEN-LAST:event_cbTypeActionPerformed

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}

		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new ManagerFrame().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JComboBox cbField;
	private javax.swing.JComboBox cbType;
	private DateComboBox dateFrom;
	private DateComboBox dateTo;
	private javax.swing.JButton generate;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JButton rent;
	private javax.swing.JPanel reportPanel;
	private javax.swing.JButton sale;
	private javax.swing.JTextField tfAgent;
	// End of variables declaration//GEN-END:variables

}
